package cn.flying.cloud.base.core.handler;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.exception.BizException;
import cn.flying.cloud.base.common.exception.CommonException;
import cn.flying.cloud.base.common.exception.RpcException;
import cn.flying.cloud.base.common.vo.Rt;


/**
 * 全局异常处理
 *
 * @author: admin
 * @date: 2022年04月02日 22:06
 * @version: 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Rt bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("业务处理异常！原因是：{}", e);
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = RpcException.class)
    @ResponseBody
    public Rt rpcExceptionHandler(HttpServletRequest req, RpcException e) {
        logger.error("rpc调用异常！原因是：{}", e);
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的公共异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public Rt flyingExceptionHandler(HttpServletRequest req, CommonException e) {
        logger.error("系统处理异常！原因是：{}", e);
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验绑定异常
     * 表单提交方式（非json使用@RequestBody接收方式）
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Rt bindExceptionHandler(HttpServletRequest req, BindException e) {
        logger.error("参数校验异常！原因是:", e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Rt.result(RtCodeEnum.R90002, errorMap);
    }

    /**
     * 处理参数校验绑定异常
     * 参数上加@RequestParam或参数加@NotBlank @NotNull等
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Rt constraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException e) {
        logger.error("参数校验异常！原因是:", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));

//        List<FieldError> fieldErrors = e.getFieldErrors();
//        Map<String, String> errorMap = new HashMap<>();
//        for (FieldError fieldError : fieldErrors) {
//            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
//        }
        return Rt.result(RtCodeEnum.R90002, message);
    }

    /**
     * 处理参数校验绑定异常
     * 前端提交的方式为json格式有效，使用@RequestBody接收方式
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Rt methodArgumentNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
        logger.error("参数校验异常！原因是:", e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Rt.result(RtCodeEnum.R90002, errorMap);
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Rt exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("系统未知异常！原因是:", e);
        return Rt.error(RtCodeEnum.R_ERROR);
    }
}
